import cv2
import numpy as np
import os
from PIL import Image
from tqdm import tqdm

def open_img(path):
    return cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1)


def findpic(big, little):
    big = open_img(big)
    little = open_img(little)
    image_x, image_y = little.shape[:2]
    result = cv2.matchTemplate(big, little, cv2.TM_CCOEFF_NORMED)  # 找图函数
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    center = (max_loc[0] + image_y / 2, max_loc[1] + image_x / 2)
    print("识别率:", max_val, "坐标", center)  # max_val：最大识别率
    return max_val, center  # 坐标



# 大津法
def otsu(image):
    ### 高和宽
    h = image.shape[0]
    w = image.shape[1]
    ### 求总像素
    m = h*w

    otsuimg = np.zeros((h, w), np.uint8)
    ##初始阈值
    initial_threshold = 0
    ### 最终阈值
    final_threshold   = 0
    # 初始化各灰度级个数统计参数
    histogram = np.zeros(256, np.int32)
    # 初始化各灰度级占图像中的分布的统计参数
    probability = np.zeros(256, np.float32)

    ### 各个灰度级的个数统计
    for i in tqdm(range(h)):
        for j in range(w):
            s = image[i,j]
            histogram[s] = histogram[s] +1
    ### 各灰度级占图像中的分布的统计参数
    for i in tqdm(range(256)):
        probability[i] = histogram[i]/m

    for i in tqdm(range(255)):
        w0 = w1 = 0  ## 前景和背景的灰度数
        fgs = bgs = 0  # 定义前景像素点灰度级总和背景像素点灰度级总和
        for j in range(256):
            if j <= i:  # 当前i为分割阈值
                w0 += probability[j]  # 前景像素点占整幅图像的比例累加
                fgs += j * probability[j]
            else:
                w1 += probability[j]  # 背景像素点占整幅图像的比例累加
                bgs += j * probability[j]
        u0 = fgs / w0  # 前景像素点的平均灰度
        u1 = bgs / w1  # 背景像素点的平均灰度
        G  = w0*w1*(u0-u1)**2
        if G >= initial_threshold:
            initial_threshold = G
            final_threshold = i
    print(final_threshold)

    for i in range(h):
        for j in range(w):
            if image[i, j] > final_threshold:
                otsuimg[i, j] = 255
            else:
                otsuimg[i, j] = 0
    return otsuimg


def gray(img_cv):
    gray_img = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
    return gray_img

if __name__ == '__main__':
    big = "C:\\Users\\朱淳\\OneDrive\\Desktop\\img\\微信图片_20211020180348.jpg"
    # little = os.path.join(os.getcwd(), "小图.jpg")
    # print(big + "\n" + little)
    # # print(findpic(big, little))
    # big = open_img(big)
    # big = gray(big)
    # cv2.imshow("OpenCV", big)
    # cv2.waitKey(0)
   # input("...")
   #  big = otsu(big)
   #  big = Image.fromarray(big)
    big = Image.open(big)
    big = big.convert('L')
    big = big.point(lambda x: 255 if x >= int(100) else 0)
    big.show()
